import { Context } from "koa";
import { UserService } from "../services/user.service";
import {
  LoginRequestDTO,
  RegisterRequestDTO,
  UpdatePasswordRequestDTO,
  UpdateUserRequestDTO,
} from "../validators/user.validator";
import { AuthUtil, TokenPayload } from "../utils/auth.util";

export class UserController {
  public static async login(ctx: Context) {
    try {
      const { mobile, password } = ctx.state.validatedBody as LoginRequestDTO;
      const user = await UserService.login({ mobile, password });

      // 生成JWT token
      const token = AuthUtil.generateToken(user.id, user.role);

      ctx.body = {
        code: 200,
        data: {
          user: {
            id: user.id,
            name: user.name,
            mobile: AuthUtil.maskMobile(user.mobile),
            role: user.role,
          },
          token: token,
        },
        message: "登录成功",
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: (error as Error).message,
      };
    }
  }

  public static async register(ctx: Context) {
    try {
      const {
        name,
        mobile,
        password,
        role = "normal",
      } = ctx.state.validatedBody as RegisterRequestDTO;
      const user = await UserService.register({ name, mobile, password, role });

      ctx.body = {
        code: 201,
        data: {
          user: {
            id: user.id,
            name: user.name,
            mobile: AuthUtil.maskMobile(user.mobile),
            role: user.role,
          },
        },
        message: "用户创建成功",
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: (error as Error).message,
      };
    }
  }

  /**
   * 更新用户信息（需要管理员权限）
   */
  public static async updateUser(ctx: Context) {
    try {
      const updateData = ctx.state.validatedBody as UpdateUserRequestDTO;
      const { id } = ctx.state.validatedParams as { id: number };
      console.log("id", typeof id, id);

      const updatedUser = await UserService.updateUser(id, updateData);

      ctx.body = {
        code: 200,
        data: {
          user: updatedUser,
        },
        message: "用户信息更新成功",
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: (error as Error).message,
      };
    }
  }

  /**
   * 获取用户列表（需要管理员权限）
   */
  public static async listUsers(ctx: Context) {
    try {
      const users = await UserService.listUsers();
      ctx.body = {
        code: 200,
        data: {
          users,
        },
        message: "用户列表获取成功",
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: (error as Error).message,
      };
    }
  }

  /**
   * 删除用户（需要管理员权限）
   */
  public static async deleteUser(ctx: Context) {
    try {
      const { id } = ctx.state.validatedParams as { id: number };
      await UserService.deleteUser(id);
      ctx.body = {
        code: 204,
        message: "用户删除成功",
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: (error as Error).message,
      };
    }
  }

  // 用户修改密码
  public static async updatePassword(ctx: Context) {
    try {
      const { userId } = ctx.state.authorization as TokenPayload;
      const { oldPassword, newPassword } = ctx.state
        .validatedBody as UpdatePasswordRequestDTO;
      await UserService.updatePassword(userId, oldPassword, newPassword);
      ctx.body = {
        code: 200,
        message: "密码更新成功",
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: (error as Error).message,
      };
    }
  }
}
